﻿using System;
using DG.Tweening;
using UI;
using UnityEngine;
using UnityEngine.Rendering.Universal;

public class MagicCube : MonoBehaviour
{
    public int m_rotateCount;
    public EItemType m_consumeItemType;
    public string m_successTriggerScenario;
    
    private Camera m_camera;

    private Transform m_selectOther;
    private Vector3 m_lastMousePosition;
    private Vector3 m_forward;

    private Transform m_tempRoot;
    
    private Collider[] m_hits = new Collider[30];

    private bool m_rotating;
    private void Awake()
    {
        m_camera = transform.Find("Camera").GetComponent<Camera>();
        Camera.main.GetComponent<UniversalAdditionalCameraData>().cameraStack.Add(m_camera);
        m_tempRoot = transform.Find("TempRoot");
        transform.localScale = Vector3.one * (1 / transform.lossyScale.x);
    }
    private void OnDestroy()
    {
        Camera.main.GetComponent<UniversalAdditionalCameraData>().cameraStack.Remove(m_camera);
    }

    private void Update()
    {
        if (m_rotating) return;
        if (Input.GetMouseButtonDown(0))
        {
            var ray = m_camera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out var cubeHit, 50f, Layers.MagicCube_Mask, QueryTriggerInteraction.Ignore))
            {
                m_selectOther = cubeHit.transform;
                m_lastMousePosition = Input.mousePosition;
                m_forward = -cubeHit.normal;
            }
        }
        else if (Input.GetMouseButtonUp(0) && m_selectOther != null)
        {
            var mouseDelta = Input.mousePosition - m_lastMousePosition;
            if (Mathf.Abs(mouseDelta.x) > Mathf.Abs(mouseDelta.y))
            {
                if (Mathf.Abs(mouseDelta.x) / Screen.width > 0.1f) //移动超过1/10个屏幕
                {
                    Rotate(m_selectOther, mouseDelta, true, mouseDelta.x < 0);
                }
            }
            else
            {
                if (Mathf.Abs(mouseDelta.y) / Screen.height > 0.1f) //移动超过1/10个屏幕
                {
                    Rotate(m_selectOther, mouseDelta, false, mouseDelta.y < 0);
                }
            }
            m_selectOther = null;
            
            m_rotateCount--;
            if (m_rotateCount <= 0)
            {
                UI_LittleGamePanel.Pass();
                if (m_consumeItemType != EItemType.None) InventoryManager.UseItem(m_consumeItemType);
                UI_ScenarioPanel.StartScenario(m_successTriggerScenario);
            }
        }
    }

    private void Rotate(Transform other, Vector3 mouseDelta, bool horizontal, bool clockwise)
    {
        m_rotating = true;
        m_tempRoot.rotation = Quaternion.identity;
        var forward = m_forward;
        if (Mathf.Abs(forward.y) > 0.5f)
        {
            horizontal = false;
            if (mouseDelta.x < 0 && mouseDelta.y < 0)
            {
                forward = new Vector3(1, 0, 0);
                clockwise = true;
            }
            else if (mouseDelta.x > 0 && mouseDelta.y > 0)
            {
                forward = new Vector3(1, 0, 0);
                clockwise = false;
            }
            else if (mouseDelta.x < 0 && mouseDelta.y > 0)
            {
                forward = new Vector3(0, 0, 1);
                clockwise = false;
            }
            else
            {
                forward = new Vector3(0, 0, 1);
                clockwise = true;
            }
        }
        var colHalfExtents = horizontal ? new Vector3(2f, 0.25f, 2f) : new Vector3(0.25f, 2f, 2f);

        //找到所有要旋转的方块
        var count = Physics.OverlapBoxNonAlloc(other.position, colHalfExtents, m_hits, Quaternion.LookRotation(forward), Layers.MagicCube_Mask, QueryTriggerInteraction.Ignore);
        for (int i = 0; i < count; i++)
        {
            var hit = m_hits[i].transform;
            hit.SetParent(m_tempRoot, true);
        }

        Quaternion targetRotation;
        if (horizontal)
        {
            targetRotation = Quaternion.AngleAxis(clockwise ? 90 : -90, Vector3.up);
        }
        else
        {
            targetRotation = Quaternion.AngleAxis(clockwise ? 90 : -90, new Vector3(-forward.z, 0, forward.x));
        }
        m_tempRoot.DORotateQuaternion(targetRotation, 0.5f).OnComplete(() =>
        {
            m_rotating = false;
            //复原父级
            for (int i = 0; i < count; i++)
            {
                var hit = m_hits[i].transform;
                hit.SetParent(transform, true);
            }
        });
    }
}